package com.yifeng.repo.micro.service.server.engine.core;

import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by daibing on 2023/3/14.
 */
@Slf4j
public class JsonRequestFilter implements Filter {
    protected final String PATH_SPLIT_REGX = "[;, ，；]";
    protected AntPathMatcher matcher = new AntPathMatcher();
    private final String[] excludePath;

    public JsonRequestFilter(String excludeUri) {
        this.excludePath = getParamToArray(excludeUri);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 1. 获取request
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 2. 排除uri
        if (this.isExcludeUri(request.getRequestURI().toLowerCase())) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 3. Wrapper支持重复读取body的场景
        if (request.getMethod().equals(HttpMethod.POST.toString())) {
            filterChain.doFilter(new JsonRequestWrapper(request), servletResponse);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    private String[] getParamToArray(String conf) {
        if (Strings.isNullOrEmpty(conf)) {
            return new String[0];
        } else {
            List<String> list = new ArrayList<>();
            String[] bs = conf.trim().split(PATH_SPLIT_REGX);
            for (String b : bs) {
                if (!Strings.isNullOrEmpty(b)) {
                    String path = b.trim().toLowerCase();
                    list.add(path.startsWith("/") ? path : "/" + path);
                }
            }
            return list.toArray(new String[0]);
        }
    }

    protected boolean isExcludeUri(String uri) {
        for (String exclude : excludePath) {
            if (this.isMatch(exclude, uri)) {
                return true;
            }
        }
        return false;
    }

    private boolean isMatch(String pattern, String uri) {
        if (pattern.contains("*") || pattern.contains("?")) {
            return matcher.match(pattern, uri);
        }
        return uri.equalsIgnoreCase(pattern);
    }
}
